package com.zhfi.dataapply.config.quartz.persons;

import com.zhfi.dataapply.entity.data.po.persons.PersonPO;
import com.zhfi.dataapply.mapper.persons.PersonMapper;
import com.zhfi.dataapply.schedule.reader.persons.PersonReader;
import com.zhfi.dataapply.schedule.writer.GeneralWriter;
import com.zhfi.dataapply.util.JobUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.*;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.item.ItemWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Slf4j
@Configuration
public class PersonConfig implements JobExecutionListener {

    public static String JOB_NAME = "person";

    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    @Autowired
    private JobUtil jobUtil;

    @Autowired
    private PersonReader reader;

    @Autowired
    private PersonMapper mapper;

    @Bean
    public Job personJob() {
        return jobBuilderFactory.get(JOB_NAME + "Job")
                .listener(this)
                .start(personStep())
                .build();
    }

    @Bean
    public Step personStep() {
        return stepBuilderFactory.get(JOB_NAME + "Step")
                .<PersonPO, PersonPO>chunk(20)
                .reader(reader)
                .writer(personWriter())
                .build();
    }

    @Bean
    public ItemWriter<PersonPO> personWriter() {
        return new GeneralWriter<>(mapper);
    }

    @Override
    public void beforeJob(JobExecution jobExecution) {
        reader.reset();
        jobUtil.doJobStart(JOB_NAME);
    }

    @Override
    public void afterJob(JobExecution jobExecution) {
        jobUtil.doRangeDateJobEnd(JOB_NAME, jobExecution);
    }

}
